//
//  StartFiveViewController.m
//  yinsiwenzhen
//
//  Created by Yangfan on 14/12/24.
//  Copyright (c) 2014年 4gread. All rights reserved.
//

#import "StartFiveViewController.h"

@interface StartFiveViewController ()

@end

@implementation StartFiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.、
    self.title = @"病情描述";
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                        [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1], NSForegroundColorAttributeName,
                        [UIFont systemFontOfSize:20],
                        NSFontAttributeName,nil]];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initStartFiveUI];
//    NSLog(@"------------获取的数据有-------------%@",_listView);
}
-(void)initStartFiveUI{
    
    _imageBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, Kwidth, Kheight-64)];
    _imageBg.backgroundColor = [UIColor clearColor];
    _imageBg.userInteractionEnabled = YES;
    [self.view addSubview:_imageBg];
    
    
    NSString *str1 = @"可提供更多文字描述";
    NSString *str2 = @"(非必填，可直接提交)";
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = [NSString stringWithFormat:@"%@",str1];
    titleLab.textColor = [UIColor colorWithRed:0.39 green:0.8 blue:0.98 alpha:1];
    titleLab.font = [UIFont systemFontOfSize:20];
    titleLab.textAlignment = NSTextAlignmentCenter;
    
    
    // 说明
    UILabel *explainLab = [[UILabel alloc] init];
    explainLab.text = [NSString stringWithFormat:@"%@",str2];
    explainLab.textColor = [UIColor colorWithRed:0.66 green:0.66 blue:0.66 alpha:1];
    explainLab.font = [UIFont systemFontOfSize:12];
    explainLab.textAlignment = NSTextAlignmentCenter;
    

    
    UIImageView *kuangImage = [[UIImageView alloc] init];
    kuangImage.image = [UIImage imageNamed:@"image_kuang"];
    kuangImage.userInteractionEnabled = YES;
    
    
    // 病情的详细描述
    _textContent = [[UITextView alloc] init];
    _textContent.backgroundColor = [UIColor clearColor];
    _textContent.font = [UIFont systemFontOfSize:14];
    _textContent.delegate = self;
    _textContent.keyboardType = UIKeyboardTypeDefault;//键盘类型
    
    [_textContent setShowsVerticalScrollIndicator:NO];
    
    
    
    _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _sureButton.backgroundColor = [UIColor colorWithRed:0.4 green:0.8 blue:0.98 alpha:1];
    [_sureButton setTitle:@"提   交" forState:UIControlStateNormal];
    _sureButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [_sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sureButton addTarget:self action:@selector(sureButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    if (isiphone6plus) {
        titleLab.frame = CGRectMake(0, 35, kScreen_Width, 30);
        explainLab.frame = CGRectMake(0, 70, kScreen_Width, 20);
        kuangImage.frame = CGRectMake(15, 100, kScreen_Width-30, 180);
        _sureButton.frame = CGRectMake(55, 290, kScreen_Width-110, 50);
    }else{
        if (isiphone4) {
           titleLab.frame = CGRectMake(0, 35, kScreen_Width, 30);
            explainLab.frame = CGRectMake(0, 70, kScreen_Width, 20);
            kuangImage.frame = CGRectMake(20, 100, kScreen_Width-40, 110);
            _sureButton.frame = CGRectMake(55, 220, kScreen_Width-110, 45);
        }else{
            titleLab.frame = CGRectMake(0, 35, kScreen_Width, 30);
            explainLab.frame = CGRectMake(0, 70, kScreen_Width, 20);
            kuangImage.frame = CGRectMake(15, 100, kScreen_Width-30, 180);
            _sureButton.frame = CGRectMake(55, 290, kScreen_Width-110, 50);
           
        }
    }
     _textContent.frame = CGRectMake(0, 0, kuangImage.frame.size.width, kuangImage.frame.size.height);
    [_imageBg addSubview:titleLab];
    [_imageBg addSubview:explainLab];
    [_imageBg addSubview:kuangImage];
    [kuangImage addSubview:_textContent];
    [_imageBg addSubview:_sureButton];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_listView.detail != nil) {
        _textContent.text = _listView.detail;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    _listView.detail = _textContent.text;
    [super viewWillDisappear:animated];
}

#pragma mark-------UItestView Delegate---------
- (void)textViewDidBeginEditing:(UITextView *)textView{
    // 开始编辑的时候开始调用
    [self keyboardDidShow:nil];
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    // 完成编辑的时候调用
    [self keyboardDidHidden];
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
    
}
// 键盘下去的时候
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_textContent resignFirstResponder];    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    return YES;
}
// 键盘上来的时候调用的方法
-(void)keyboardDidShow:(NSNotification *)notification{
    //获取键盘高度
    NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    
    [keyboardObject getValue:&keyboardRect];
    
    //调整放置有textView的view的位置
    //设置动画
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    //设置发布的按钮网上移动
//    int autoHeight = Kheight -64 - keyboardRect.size.height+10;//高度
//    _saveButton.frame = CGRectMake(15, autoHeight, Kwidth-29, 50);
    if (isiphone6plus) {
        _imageBg.frame = CGRectMake(0, 64, Kwidth, Kheight);
    }else{
        _imageBg.frame = CGRectMake(0, keyboardRect.size.height-30, Kwidth, Kheight);
    }
    
    [UIView commitAnimations];

}
-(void)keyboardDidHidden{
    _imageBg.frame = CGRectMake(0, 64, Kwidth, Kheight-64);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_textContent resignFirstResponder];
    [self.view endEditing:YES];
}
#pragma mark---UIButtonClick
// 点击提交按钮的时候
-(void)sureButtonClick:(UIButton *)sender{
    [_textContent resignFirstResponder];
    [_sureButton resignFirstResponder];
    [self keyboardDidHidden];
    [self showIndeterminateProgress:@"正在全力上传保护您的隐私"];
    [self saveInquiryGata];
    [HUD hide:YES];
}
#pragma mark---------UIAlertView Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [HUD hide:YES];
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}
// 定时器的方法
-(void)performDismiss:(NSTimer *)timer{

    [self.navigationController popToRootViewControllerAnimated:YES];
//    [self saveInquiryGata];

}
// 保存问诊数据
-(void)saveInquiryGata{
    
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *myString = [userDefaultes stringForKey:@"personage"];// 获取本地数据
//    NSLog(@"------获取本地存储的数据是-----%@",myString);
    // 保存数据 基本数据的存储
    AVObject *inquiry = [[AVObject alloc] initWithClassName:@"diseaseRecord"];
    if ([_textContent.text isEqualToString:@""] ) {
        [inquiry setObject:@"没有描述" forKey:@"diseaseDescribe"];// 病情的描述
    }else{
        [inquiry setObject:_textContent.text forKey:@"diseaseDescribe"];// 病情的描述
    }
    [inquiry setObject:_listView.howLong forKey:@"diseaseTime"];// 病情的时间
    [inquiry addUniqueObjectsFromArray:[NSMutableArray arrayWithObjects:_listView.howAboutArr, nil] forKey:@"diseaseFeel"];// 病患处的感觉 （多种选项，数组形式）
    [inquiry setObject:[NSNumber numberWithBool:_listView.donotDrug] forKey:@"whetherPharmacy"];// 是否已经用药  ifHandle
    [inquiry setObject:[NSNumber numberWithBool:NO] forKey:@"ifHandle"];// 是否已经处理
    [inquiry save];
    [inquiry saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            _objectId = inquiry.objectId;
            //        NSLog(@"-------------------%@",_objectId);
            [self imageSave];
            [self whetherPharmacyImageSave];
        }else{
            
        }
       
    }];

    
    AVQuery *query = [[AVQuery alloc]initWithClassName:@"equipmentId"];
    AVObject *object = [query getObjectWithId:myString];
    AVRelation *relation=[object relationforKey:@"diseaseRelation"];
    [relation addObject:inquiry];
    [object save];
    [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        UIAlertView *hintAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您已成功提交您的信息" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        hintAlertView.delegate = self;
        [hintAlertView show];

    }];
    

   
}
// 图片的保存
-(void)imageSave{
//    NSLog(@"---------病图的存储----------%@",_objectId);
    for (int i = 0 ; i < _listView.privacyImages.count; i++) {
        UIImage *image = [_listView.privacyImages objectAtIndex:i];
        
        // 病情照片的上传存储
        //image  比如你有一个叫 "image" 的 UIImage 对象
        NSData *imageData = UIImagePNGRepresentation(image);
        AVFile *imageFile = [AVFile fileWithName:@"ad" data:imageData];
        [imageFile save];
        [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            AVObject *userPhoto = [AVObject objectWithClassName:@"diseaseImage"];
            [userPhoto setObject:imageFile forKey:@"diseaseImages"];
            [userPhoto save];
            [userPhoto saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                AVQuery *PharmacyQuery = [[AVQuery alloc]initWithClassName:@"diseaseRecord"];
                AVObject *object1 = [PharmacyQuery getObjectWithId:_objectId];
                AVRelation *relation=[object1 relationforKey:@"diseaseImageRelation"];
                [relation addObject:userPhoto];
                [object1 save];
            }];
        }];
        
       
        
        
    }

}
// 是否用药图片的存储
-(void)whetherPharmacyImageSave{
//    NSLog(@"---------药图的存储----------%@",_objectId);
    if (_listView.donotDrug == YES) {
        NSData *imageData = UIImagePNGRepresentation(_listView.imageDrug);
        //    NSString *result = [[NSString alloc] initWithData:imageData  encoding:NSUTF8StringEncoding];
        AVFile *imageFile = [AVFile fileWithName:@"test" data:imageData];
        [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            AVObject *drugPhoto = [AVObject objectWithClassName:@"drugImage"];
            [drugPhoto setObject:imageFile forKey:@"drugImage"];
            [drugPhoto save];
            [drugPhoto saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                AVQuery *PharmacyQuery = [[AVQuery alloc]initWithClassName:@"diseaseRecord"];
                AVObject *drugObject = [PharmacyQuery getObjectWithId:_objectId];
                AVRelation *drugRelation=[drugObject relationforKey:@"drugImageRelation"];
                [drugRelation addObject:drugPhoto];
                [drugObject save];
            }];

        }];
    }


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
